import React, { useState, useRef, useEffect, useContext } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Modal,
  Image,
  TouchableWithoutFeedback,
  ScrollView,
  Alert,
  Dimensions,
  ActivityIndicator,
} from "react-native";
import UserProblemContext from "../../../context/questionnaire/UserProblem";
import MyQuesContext from "../../../context/questionnaire/MyQuesContext";
import ShowChoiceQues from "../../../components/showSubject/showChoiceQues";
import ShowEssayQues from "../../../components/showSubject/ShowEssayQues";
import LoadingBar from "../../../components/InterView/LoadingBar";

import ShowFileData from "../../../components/showSubject/showFileData";

import * as ImagePicker from "expo-image-picker";
import ImageViewer from "react-native-image-zoom-viewer";
import VideoPlayer from "expo-video-player";
import { Audio } from "expo-av";
import * as DocumentPicker from "expo-document-picker";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import { ResizeMode } from "expo-av";
import { Feather } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import { Foundation } from "@expo/vector-icons";
import AudioListItem from "../../../components/InterView/AudioListItem";
import { play, pause, resume, playNext } from "../../../utils/audioController";
import { fileWeb } from "../../../api/query";

const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window");

const Loading = ({ text }) => {
  return (
    <View style={styles.alterView}>
      <ActivityIndicator animating={true} size={"large"} color="#bbb" />
      <Text style={{ color: "#aaa", marginTop: 10 }}>{text}</Text>
    </View>
  );
};

const CompleteProblem = ({ navigation, route }) => {
  const { myQuesIndex, flag, showProData } = route.params;
  const { UserProblem } = useContext(UserProblemContext);
  const ProTemplate = UserProblem.problem[1];
  const { userProLoading, editQuesProblem } = useContext(MyQuesContext);

  // 该问卷为题清单为空时，展示空白问题清单来填写
  const [ProblemBody, setProblemBody] = useState([[], []]);
  // 每个问题是否展开，默认展开
  const [visibleArr, setVisibleArr] = useState([]);

  useEffect(() => {
    if (showProData.problem.length == 0) {
      setProblemBody(JSON.parse(JSON.stringify(UserProblem.problem)));
    } else {
      setProblemBody(JSON.parse(JSON.stringify(showProData.problem)));
    }
  }, []);

  useEffect(() => {
    for (let i = 0; i < ProblemBody.length; i++) {
      setVisibleArr([...visibleArr, true]);
    }
  }, [ProblemBody]);

  const editAnswer = async (key1, key2, key3, answer) => {
    console.log("答案", answer.answer);
    let t_pro = JSON.parse(JSON.stringify(ProblemBody));
    t_pro[key1][key2] = { ...t_pro[key1][key2], answer: answer.answer };
    // await setProblemBody((preProblemBody) => {
    //   return preProblemBody.map((item1, index1) => {
    //     return item1.map((item2, index2) => {
    //       if (index1 == key1 && index2 == key2) {
    //         return { ...item2, answer: answer.answer };
    //       } else {
    //         return { ...item2 };
    //       }
    //     });
    //   });
    // });
    setProblemBody(JSON.parse(JSON.stringify([...t_pro])));
    console.log("有答案啦---", ProblemBody);
  };
  //加载可见性
  const [isConfirm, setIsConfirm] = useState(false);
  //拍照/打开相册可见性
  const [isVisible, setIsVisible] = useState(false);
  //摄像/打开相册可见性
  const [isVideoVisible, setIsVideoVisible] = useState(false);

  const [imageList, setImageList] = useState([]);
  //原始需保留的问题图片
  const [originImage, setOriginImage] = useState(showProData.image);
  //原始需删除的问题图片
  const [deleteOriginImage, setDeleteOriginImage] = useState([]);
  //放大图片
  const [magnifypVisible, setMagnifypVisible] = useState(false);
  const [index, setIndex] = useState(0);
  const [imagesUrl, setimagesUrl] = useState([]);
  // 音频
  const [audioList, setAudioList] = useState([]);
  //原始需保留的问题音频
  const [originAudio, setOriginAudio] = useState(showProData.soundfile);
  //原始需删除的问题音频
  const [deleteOriginAudio, setDeleteOriginAudio] = useState([]);
  const [currentAudio, setCurrentAudio] = useState({});
  const [currentAudioIndex, setCurrentAudioIndex] = useState(null);
  const [soundObj, setSoundObj] = useState(null);
  const [playbackObj, setPlaybackObj] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  //视频
  const refVideo = useRef(null);
  const [videoList, setvideoList] = useState([]);
  //原始需保留的问题视频
  const [originVideo, setOriginVideo] = useState(showProData.video);
  //原始需删除的问题视频
  const [deleteOriginVideo, setDeleteOriginVideo] = useState([]);
  const [inFullscreen, setInFullsreen] = useState(false);
  //保存图片时需要MediaLibrary的权限
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();

  useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      getPermission();
    }
    return () => {
      isMounted = false;
    };
  }, []);

  const permissionAllert = () => {
    Alert.alert("权限请求", "本App需要读取系统媒体库的权限", [
      {
        text: "允许",
        onPress: () => getPermission(),
      },
      {
        text: "不允许",
        onPress: () => alert("未授权访问媒体库的权限，请在设置中进行修改"),
      },
    ]);
  };

  const getPermission = async () => {
    const permission = await MediaLibrary.getPermissionsAsync();
    if (permission.granted) {
      setHasMediaLibraryPermission(true);
    }
    if (!permission.granted && permission.canAskAgain) {
      const { status, canAskAgain } =
        await MediaLibrary.requestPermissionsAsync();
      if (status === "granted") {
        setHasMediaLibraryPermission(true);
      }
      if (status === "denied" && canAskAgain) {
        permissionAllert();
      }
      if (status === "denied" && !canAskAgain) {
        alert("未授权访问媒体库的权限，请在设置中进行修改");
      }
    }
    if (!permission.canAskAgain && !permission.granted) {
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      // aspect: [1, 1],
      quality: 1,
    });
    if (!result.cancelled) {
      setImageList([...imageList, result.uri]);
      setIsVisible(false);
    }
  };

  const openCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setImageList([...imageList, result.uri]);
      setIsVisible(false);
    }
  };

  //  Unlike saveImageToPhone(), This method doesn't return created asset. On iOS 11+, it's possible to use this method without asking for CAMERA_ROLL permission.
  const saveImage = async (url) => {
    setIsConfirm(true);
    if (url.substring(0, 7) != "file://") {
      const localpicture = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + "image.jpg"
      );
      if (localpicture.status != 200) {
        alert("下载失败！");
      } else {
        url = localpicture.uri;
      }
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsConfirm(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsConfirm(false);
        alert("保存时出错了！");
      }
    } else {
      setIsConfirm(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const deleteImage = (url) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let images = imageList.filter((item) => item !== url);
          setImageList(images);
        },
      },
    ]);
  };

  const deleteOriImage = (image) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let images = originImage.filter((item) => item != image);
          setOriginImage(images);
          setDeleteOriginImage([...deleteOriginImage, image]);
        },
      },
    ]);
  };

  const pickVideo = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: true,
      quality: 1,
    });
    if (!result.cancelled) {
      setvideoList([...videoList, result.uri]);
      setIsVideoVisible(false);
    }
  };

  const openVideoCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setvideoList([...videoList, result.uri]);
      setIsVideoVisible(false);
    }
  };

  const saveVideo = async (url) => {
    setIsConfirm(true);
    if (url.substring(0, 7) != "file://") {
      const localvideo = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + "video.mp4"
      );
      console.log(localvideo);
      if (localvideo.status != 200) {
        setIsConfirm(false);
        alert("下载失败！");
      } else {
        url = localvideo.uri;
      }
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsConfirm(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsConfirm(false);
        alert("保存时出错了！");
      }
    } else {
      setIsConfirm(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveVideoAlert = (url) => {
    Alert.alert("提示", "要保存这个视频吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          saveVideo(url);
        },
      },
    ]);
  };

  const deleteVideo = (url) => {
    Alert.alert("提示", "要删除这个视频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let videos = videoList.filter((item) => item !== url);
          setvideoList(videos);
        },
      },
    ]);
  };

  const deleteOriVideo = (video) => {
    Alert.alert("提示", "要删除这张视频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let videos = originVideo.filter((item) => item != video);
          setOriginVideo(videos);
          setDeleteOriginVideo([...deleteOriginVideo, video]);
        },
      },
    ]);
  };

  const pickAudio = async () => {
    let result = await DocumentPicker.getDocumentAsync({});
    if (result.type != "cancel") {
      if (result.mimeType.substring(0, 5) != "audio") {
        alert("请选择音频文件");
      } else {
        setAudioList([...audioList, { uri: result.uri, name: result.name }]);
      }
    }
  };

  const deleteAudio = (audio) => {
    Alert.alert("提示", "要删除这个音频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let audios = audioList.filter((item) => item !== audio);
          setAudioList(audios);
        },
      },
    ]);
  };

  const deleteOriAudio = (audio) => {
    Alert.alert("提示", "要删除这个音频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let audios = originAudio.filter((item) => item != audio);
          setOriginAudio(audios);
          setDeleteOriginAudio([...deleteOriginAudio, audio]);
        },
      },
    ]);
  };

  const saveAudio = async (type, aduio) => {
    setIsConfirm(true);
    let url;
    if (type == 0) {
      url = fileWeb + "/" + aduio.filePath;
      const localvideo = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + url.split("/").pop()
      );
      if (localvideo.status != 200) {
        setIsConfirm(false);
        alert("下载失败！");
      } else {
        url = localvideo.uri;
      }
    } else {
      url = aduio.uri;
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsConfirm(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsConfirm(false);
        alert("保存时出错了！");
      }
    } else {
      setIsConfirm(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveAudioAlert = (type, audio) => {
    Alert.alert("提示", "要保存这个录音吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          saveAudio(type, audio);
        },
      },
    ]);
  };

  //处理录音点击事件
  const handleAudioPress = async (audio) => {
    let index;
    let tag;
    if (originAudio.indexOf(audio) != -1) {
      index = originAudio.indexOf(audio);
      tag = 1;
    } else {
      index = audioList.indexOf(audio) + originAudio.length;
      tag = 2;
    }
    // playing audio for the first time.
    if (soundObj === null) {
      const playbackObj = new Audio.Sound();
      let status;
      if (tag == 1) {
        status = await play(playbackObj, fileWeb + "/" + audio.filePath);
      } else {
        status = await play(playbackObj, audio.uri);
      }
      setCurrentAudio(audio);
      setCurrentAudioIndex(index);
      setIsPlaying(true);
      setPlaybackObj(playbackObj);
      setSoundObj(status);

      playbackObj.setOnPlaybackStatusUpdate((playbackStatus) => {
        if (playbackStatus.didJustFinish) {
          setCurrentAudio({});
          setCurrentAudioIndex(null);
          setIsPlaying(false);
          setPlaybackObj(null);
          setSoundObj(null);
        }
      });
    } else {
      // pause audio
      if (
        soundObj.isLoaded &&
        soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await pause(playbackObj);
        setSoundObj(status);
        setIsPlaying(false);
      }
      // resume audio
      if (
        soundObj.isLoaded &&
        !soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await resume(playbackObj);
        setSoundObj(status);
        setIsPlaying(true);
      }
      // select another audio
      if (soundObj.isLoaded && index !== currentAudioIndex) {
        let status;
        if (tag == 1) {
          status = await playNext(playbackObj, fileWeb + "/" + audio.filePath);
        } else {
          status = await playNext(playbackObj, audio.uri);
        }
        setCurrentAudio(audio);
        setSoundObj(status);
        setIsPlaying(true);
        setCurrentAudioIndex(index);
      }
    }
  };

  const confirmEdit = async () => {
    setIsEditing(true);
    let userproblem = {
      ...showProData,
      time: new Date(),
      problem: ProblemBody,
      image: imageList,
      soundfile: audioList,
      video: videoList,
    };
    console.log("录音文件---", audioList);
    // editQuesProblem(myQuesIndex, ProblemBody);
    let isSuccess = true;
    await editQuesProblem(
      myQuesIndex,
      userproblem,
      originImage,
      deleteOriginImage,
      originAudio,
      deleteOriginAudio,
      originVideo,
      deleteOriginVideo,
      (value) => {
        isSuccess = value;
      }
    );
    setIsEditing(false);
    if (isSuccess) {
      navigation.goBack();
    }
  };

  const [isEditing, setIsEditing] = useState(false);
  const handleUpdatePro = async () => {
    await confirmEdit();
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isConfirm} />
      <ScrollView>
        <View style={{ marginTop: 10 }}>
          {/* <View
            style={{
              marginTop: 20,
              alignItems: "center",
              marginBottom: 10,
            }}
          >
            <Text style={{ fontSize: 19, fontWeight: "bold" }}>问题清单</Text>
          </View> */}
          {flag == "show" && ProblemBody.length == 0 ? (
            <View>
              <View
                style={{
                  alignItems: "center",
                }}
              >
                <Text style={{ fontSize: 17, fontWeight: "bold" }}>
                  问题清单
                </Text>
              </View>
              <View
                style={{
                  alignItems: "center",
                  marginTop: 10,
                  marginBottom: 20,
                }}
              >
                <Text style={{ color: "#ddd" }}>暂无问题</Text>
              </View>
            </View>
          ) : (
            <View>
              {ProblemBody.map((content, index1) => {
                return (
                  <View key={index1}>
                    {index1 != 0 ? (
                      <TouchableOpacity
                        onPress={() => {
                          // t_arr[index1] = !t_arr[index1];
                          // setVisibleArr(t_arr);
                          setVisibleArr((preArr) => {
                            return preArr.map((item, index) => {
                              return index == index1 ? !item : item;
                            });
                          });
                          // console.log(visibleArr);
                        }}
                      >
                        <View
                          style={{
                            marginTop: 25,
                            alignItems: "center",
                            marginBottom: 10,
                          }}
                        >
                          <Text style={{ fontSize: 16, fontWeight: "bold" }}>
                            {"问题" + index1}
                          </Text>
                        </View>
                      </TouchableOpacity>
                    ) : null}
                    {visibleArr[index1] ? (
                      <View>
                        {content.map((question, index) => {
                          if (question.type == 1) {
                            return (
                              <View key={index}>
                                <ShowEssayQues
                                  isEdit={flag == "show" ? false : true}
                                  flag={[index1, index]}
                                  editAnswer={editAnswer}
                                  number={index1 == 0 ? "" : index + 1}
                                  QuesContent={question}
                                ></ShowEssayQues>
                              </View>
                            );
                          }
                          if (question.type == 2 || 3) {
                            return (
                              <View key={index}>
                                <ShowChoiceQues
                                  isEdit={flag == "show" ? false : true}
                                  flag={[index1, index]}
                                  editAnswer={editAnswer}
                                  number={index + 1}
                                  QuesContent={question}
                                ></ShowChoiceQues>
                              </View>
                            );
                          }
                        })}
                      </View>
                    ) : null}
                  </View>
                );
              })}
            </View>
          )}
          <View></View>

          {flag == "show" ? (
            <View>
              <ShowFileData
                filedata={{
                  image: showProData.image,
                  soundfile: showProData.soundfile,
                  video: showProData.video,
                }}
              ></ShowFileData>
            </View>
          ) : (
            <View>
              <View
                style={{
                  marginTop: 25,
                  alignItems: "center",
                  marginBottom: 40,
                }}
              >
                <Text style={{ fontSize: 16, fontWeight: "bold" }}>
                  添加资料
                </Text>
              </View>
              <View>
                {/* 上传图片 */}
                <View style={styles.section}>
                  <View style={styles.tagItem}>
                    <Text style={styles.tagtitle}>问题图片</Text>
                    {/* 点击+号添加图片 */}
                    {imageList.length != 0 || originImage.length != 0 ? (
                      <TouchableOpacity
                        onPress={() => {
                          setIsVisible(true);
                        }}
                        style={styles.smalladdimage}
                      >
                        <MaterialIcons
                          name="add-a-photo"
                          size={20}
                          color="#bcbcbc"
                        />
                      </TouchableOpacity>
                    ) : null}
                  </View>

                  {/* 点击+号添加图片 */}
                  {imageList.length == 0 && originImage.length == 0 ? (
                    <TouchableOpacity
                      onPress={() => {
                        setIsVisible(true);
                      }}
                      style={[styles.addimage, { marginLeft: 15 }]}
                    >
                      <MaterialIcons
                        name="add-a-photo"
                        size={40}
                        color="#bcbcbc"
                      />
                    </TouchableOpacity>
                  ) : null}

                  {/* 图片列表 */}
                  <View style={styles.imageList}>
                    {/* 原始图片 */}
                    {originImage.map((image, index) => {
                      return (
                        <View key={index}>
                          {/* 删除图片按钮 */}
                          <TouchableOpacity
                            onPress={() => {
                              deleteOriImage(image);
                            }}
                            style={
                              index % 3 == 2
                                ? styles.lastcoldeleteimage
                                : styles.deleteimage
                            }
                          >
                            <Feather
                              name="x"
                              size={15}
                              color="#ffffff"
                              style={{ zIndex: 10 }}
                            />
                          </TouchableOpacity>
                          {/* 图片列表，点击放大 */}
                          <TouchableOpacity
                            onPress={() => {
                              let originImageUrl = originImage.map((item) => {
                                return fileWeb + "/" + item.filePath;
                              });
                              let newimageList = [
                                ...originImageUrl,
                                ...imageList,
                              ].map((item) => ({
                                url: item,
                                props: {},
                              }));
                              setimagesUrl(newimageList);
                              setIndex(index);
                              setMagnifypVisible(true);
                            }}
                          >
                            <Image
                              source={{ uri: fileWeb + "/" + image.filePath }}
                              loadingIndicatorSource={require("../../../../assets/interview/loading.png")}
                              style={[
                                index % 3 == 2
                                  ? styles.lascolsingleimage
                                  : styles.singleimage,
                                { resizeMode: "cover" },
                              ]}
                            />
                          </TouchableOpacity>
                        </View>
                      );
                    })}
                    {imageList.map((imageurl, index) => {
                      return (
                        <View key={index}>
                          {/* 删除图片按钮 */}
                          <TouchableOpacity
                            onPress={() => {
                              deleteImage(imageurl);
                            }}
                            style={
                              (index + originImage.length) % 3 == 2
                                ? styles.lastcoldeleteimage
                                : styles.deleteimage
                            }
                          >
                            <Feather
                              name="x"
                              size={15}
                              color="#ffffff"
                              style={{ zIndex: 10 }}
                            />
                          </TouchableOpacity>
                          {/* 图片列表，点击放大 */}
                          <TouchableOpacity
                            onPress={() => {
                              let originImageUrl = originImage.map((item) => {
                                return fileWeb + "/" + item.filePath;
                              });
                              let newimageList = [
                                ...originImageUrl,
                                ...imageList,
                              ].map((item) => ({
                                url: item,
                                props: {},
                              }));
                              setimagesUrl(newimageList);
                              setIndex(index + originImage.length);
                              setMagnifypVisible(true);
                            }}
                          >
                            <Image
                              source={{ uri: imageurl }}
                              style={[
                                (index + originImage.length) % 3 == 2
                                  ? styles.lascolsingleimage
                                  : styles.singleimage,
                                { resizeMode: "cover" },
                              ]}
                            />
                          </TouchableOpacity>
                        </View>
                      );
                    })}
                  </View>

                  {/* 拍照/打开相机Modal */}
                  <Modal
                    animationType="fade"
                    transparent={true}
                    visible={isVisible}
                  >
                    <View style={styles.ModalBackground}></View>

                    <TouchableWithoutFeedback
                      onPress={() => {
                        setIsVisible(false);
                      }}
                    >
                      <View style={styles.ModalTop}></View>
                    </TouchableWithoutFeedback>

                    <View style={styles.ModalStyle}>
                      <TouchableOpacity
                        style={styles.ModalOption}
                        onPress={() => {
                          openCamera();
                        }}
                      >
                        <Text style={styles.ModalText}>拍摄</Text>
                      </TouchableOpacity>

                      <TouchableOpacity
                        style={[styles.ModalOption, { borderBottomWidth: 4 }]}
                        onPress={() => pickImage()}
                      >
                        <Text style={styles.ModalText}>从相册选择</Text>
                      </TouchableOpacity>

                      <TouchableOpacity
                        style={styles.ModalOption}
                        onPress={() => {
                          setIsVisible(false);
                        }}
                      >
                        <Text style={styles.ModalText}>取消</Text>
                      </TouchableOpacity>
                    </View>
                  </Modal>
                </View>

                {/* 放大图片 */}
                <Modal visible={magnifypVisible} animationType={"fade"}>
                  <ImageViewer
                    imageUrls={imagesUrl}
                    menuContext={{ saveToLocal: "保存图片", cancel: "取消" }}
                    loadingRender={() => {
                      () => {
                        return (
                          <View>
                            <ActivityIndicator
                              animating={true}
                              size={"large"}
                            />
                          </View>
                        );
                      };
                    }}
                    index={index}
                    onClick={() => {
                      setMagnifypVisible(false);
                    }}
                    onSave={() => {
                      saveImage(imagesUrl[index].url);
                    }}
                  />
                </Modal>

                {/* 上传录音 */}
                <View style={styles.section}>
                  <View style={styles.tagItem}>
                    <Text style={styles.tagtitle}>问题录音</Text>
                    {/* 添加录音按钮 */}
                    {audioList.length != 0 || originAudio.length != 0 ? (
                      <TouchableOpacity
                        onPress={() => {
                          pickAudio();
                        }}
                        style={[styles.smalladdimage]}
                      >
                        <Foundation name="record" size={20} color="#bcbcbc" />
                      </TouchableOpacity>
                    ) : null}
                  </View>
                  {/* 添加录音按钮 */}
                  {audioList.length == 0 && originAudio.length == 0 ? (
                    <TouchableOpacity
                      onPress={() => {
                        pickAudio();
                      }}
                      style={[styles.addimage, { marginLeft: 15 }]}
                    >
                      <Foundation name="record" size={45} color="#bcbcbc" />
                    </TouchableOpacity>
                  ) : null}

                  <View style={styles.audiolistStyle}>
                    {originAudio.map((item, index) => {
                      return (
                        <AudioListItem
                          key={index}
                          audioName={"录音" + (index + 1)}
                          isPlaying={isPlaying}
                          activeListItem={currentAudioIndex === index}
                          onAudioPress={() => handleAudioPress(item)}
                          deleteAudio={() => deleteOriAudio(item)}
                          downloadAudio={() => {
                            saveAudioAlert(0, item);
                          }}
                        />
                      );
                    })}
                    {audioList.map((item, index) => {
                      return (
                        <AudioListItem
                          key={index}
                          audioName={item.name}
                          isPlaying={isPlaying}
                          activeListItem={
                            currentAudioIndex === index + originAudio.length
                          }
                          onAudioPress={() => handleAudioPress(item)}
                          deleteAudio={() => deleteAudio(item)}
                          downloadAudio={() => {
                            saveAudioAlert(1, item);
                          }}
                        />
                      );
                    })}
                  </View>
                </View>

                {/* 上传视频 */}
                <View style={styles.section}>
                  <View style={styles.tagItem}>
                    <Text style={styles.tagtitle}>问题视频</Text>
                    {/* 添加视频按钮 */}
                    {videoList.length != 0 || originVideo.length != 0 ? (
                      <TouchableOpacity
                        onPress={() => {
                          setIsVideoVisible(true);
                        }}
                        style={[styles.smalladdimage]}
                      >
                        <MaterialIcons
                          name="video-collection"
                          size={20}
                          color="#bcbcbc"
                        />
                      </TouchableOpacity>
                    ) : null}
                  </View>

                  {/* 添加视频按钮 */}
                  {originVideo == 0 && videoList.length == 0 ? (
                    <TouchableOpacity
                      onPress={() => {
                        setIsVideoVisible(true);
                      }}
                      style={[styles.addimage, { marginLeft: 15 }]}
                    >
                      <MaterialIcons
                        name="video-collection"
                        size={40}
                        color="#bcbcbc"
                      />
                    </TouchableOpacity>
                  ) : null}

                  <View style={styles.videoList}>
                    {/* 原始视频 */}
                    {originVideo.map((video, index) => {
                      return (
                        <View key={index}>
                          {/* 删除视频的按钮 */}
                          <TouchableOpacity
                            onPress={() => {
                              deleteOriVideo(video);
                            }}
                            style={styles.deletevideo}
                          >
                            <Feather
                              name="x"
                              size={19}
                              color="#ffffff"
                              style={{ zIndex: 10 }}
                            />
                          </TouchableOpacity>
                          {/* 下载视频的按钮 */}
                          <TouchableOpacity
                            onPress={() => {
                              saveVideoAlert(fileWeb + "/" + video.filePath);
                            }}
                            style={styles.downloadvideo}
                          >
                            <Feather
                              name="download"
                              size={19}
                              color="#ffffff"
                              style={{ zIndex: 10 }}
                            />
                          </TouchableOpacity>
                          {/* 视频列表 */}
                          <View style={{ marginBottom: 10 }}>
                            <VideoPlayer
                              videoProps={{
                                shouldPlay: false,
                                resizeMode: ResizeMode.CONTAIN,
                                source: {
                                  uri: fileWeb + "/" + video.filePath,
                                },
                              }}
                              style={{
                                height: inFullscreen
                                  ? DEVICE_WIDTH
                                  : (DEVICE_WIDTH * 3) / 5,
                                width: inFullscreen
                                  ? DEVICE_HEIGHT
                                  : (DEVICE_WIDTH * 4) / 5,
                                videoBackgroundColor: "#000000",
                              }}
                            />
                          </View>
                        </View>
                      );
                    })}
                    {/* 新增视频 */}
                    {videoList.map((videourl, index) => {
                      return (
                        <View key={index}>
                          {/* 删除视频的按钮 */}
                          <TouchableOpacity
                            onPress={() => {
                              deleteVideo(videourl);
                            }}
                            style={styles.deletevideo}
                          >
                            <Feather
                              name="x"
                              size={19}
                              color="#ffffff"
                              style={{ zIndex: 10 }}
                            />
                          </TouchableOpacity>
                          {/* 下载视频的按钮 */}
                          <TouchableOpacity
                            onPress={() => {
                              saveVideoAlert(videourl);
                            }}
                            style={styles.downloadvideo}
                          >
                            <Feather
                              name="download"
                              size={19}
                              color="#ffffff"
                              style={{ zIndex: 10 }}
                            />
                          </TouchableOpacity>
                          {/* 视频列表 */}
                          <View style={{ marginBottom: 10 }}>
                            <VideoPlayer
                              videoProps={{
                                shouldPlay: false,
                                resizeMode: ResizeMode.CONTAIN,
                                source: {
                                  uri: videourl,
                                },
                              }}
                              // fullscreen={{
                              //   inFullscreen: inFullscreen,
                              //   enterFullscreen: async () => {
                              //     setStatusBarHidden(true, "fade");
                              //     setInFullsreen(!inFullscreen);
                              //     await ScreenOrientation.lockAsync(
                              //       ScreenOrientation.OrientationLock.LANDSCAPE_LEFT
                              //     );
                              //     refVideo.current.playAsync();
                              //   },
                              //   exitFullscreen: async () => {
                              //     setStatusBarHidden(false, "fade");
                              //     setInFullsreen(!inFullscreen);
                              //     await ScreenOrientation.lockAsync(
                              //       ScreenOrientation.OrientationLock.PORTRAIT
                              //     );
                              //     refVideo.current.pauseAsync();
                              //   },
                              // }}
                              style={{
                                height: inFullscreen
                                  ? DEVICE_WIDTH
                                  : (DEVICE_WIDTH * 3) / 5,
                                width: inFullscreen
                                  ? DEVICE_HEIGHT
                                  : (DEVICE_WIDTH * 4) / 5,
                                videoBackgroundColor: "#000000",
                              }}
                            />
                          </View>
                        </View>
                      );
                    })}

                    {/* 摄像/打开相册Modal */}
                    <Modal
                      animationType="fade"
                      transparent={true}
                      visible={isVideoVisible}
                    >
                      <View style={styles.ModalBackground}></View>

                      <TouchableWithoutFeedback
                        onPress={() => {
                          setIsVideoVisible(false);
                        }}
                      >
                        <View style={styles.ModalTop}></View>
                      </TouchableWithoutFeedback>

                      <View style={styles.ModalStyle}>
                        <TouchableOpacity
                          style={styles.ModalOption}
                          onPress={() => {
                            openVideoCamera();
                          }}
                        >
                          <Text style={styles.ModalText}>摄像</Text>
                        </TouchableOpacity>

                        <TouchableOpacity
                          style={[styles.ModalOption, { borderBottomWidth: 4 }]}
                          onPress={() => pickVideo()}
                        >
                          <Text style={styles.ModalText}>从相册选择</Text>
                        </TouchableOpacity>

                        <TouchableOpacity
                          style={styles.ModalOption}
                          onPress={() => {
                            setIsVideoVisible(false);
                          }}
                        >
                          <Text style={styles.ModalText}>取消</Text>
                        </TouchableOpacity>
                      </View>
                    </Modal>
                  </View>
                </View>
              </View>
            </View>
          )}
        </View>
      </ScrollView>
      {flag == "show" ? null : (
        <View style={styles.btnBox}>
          <TouchableOpacity
            style={styles.backBtn}
            onPress={() => {
              // newProblem();
              let t_pro = JSON.parse(JSON.stringify(ProblemBody));
              t_pro.push(ProTemplate);
              setProblemBody(JSON.parse(JSON.stringify([...t_pro])));
              // t_arr.push(true);
              setVisibleArr([...visibleArr, true]);
            }}
          >
            <Text style={{ color: "#41C3EE" }}>添加问题</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.submitBtn}
            onPress={() => {
              // addQues({ type: 0, head: groupTitle, contents: quesArr });
              // updateProAnswer(ProblemBody);
              handleUpdatePro();
            }}
          >
            <Text style={{ color: "#fff" }}>保存</Text>
          </TouchableOpacity>
        </View>
      )}
      <Modal animationType="fade" transparent={true} visible={isEditing}>
        <Loading text="添加中"></Loading>
      </Modal>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "white",
    // alignItems: "center",
    justifyContent: "center",
    // backgroundColor: "#eee",
  },
  optionBtn: {
    height: 40,
    width: 250,
    marginTop: 15,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#41C3EE",
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.5, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalTop: {
    flex: 1,
  },
  modalOption: {
    // backgroundColor: "yellow",
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  modalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
  backBtn: {
    flex: 5,
    borderWidth: 1,
    borderColor: "#41C3EE",
    // alignContent: "center",
    // justifyContent: "center",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
  },
  submitBtn: {
    flex: 3.5,
    marginLeft: "6%",
    backgroundColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
  },
  btnBox: {
    flexDirection: "row",
    marginLeft: "5%",
    marginRight: "5%",
    marginTop: 10,
    marginBottom: 10,
  },
  section: {
    marginLeft: 20,
    marginBottom: 20,
    marginRight: 20,
  },
  tagItem: {
    borderBottomWidth: 1,
    borderBottomColor: "#cccccc",
    paddingBottom: 5,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 15,
  },
  tagtitle: {
    fontSize: 18,
    marginLeft: 10,
    fontWeight: "bold",
  },
  tagborder: {
    width: DEVICE_WIDTH / 4,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#d1d1d6",
    borderRadius: 2,
    marginBottom: 10,
  },
  tag: {
    color: "#d1d1d6",
    fontSize: 14,
    includeFontPadding: false,
    textAlignVertical: "center",
    paddingBottom: 4,
    paddingTop: 4,
  },
  //问题图片位置信息
  imageList: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "flex-start",
    alignContent: "center",
    paddingHorizontal: ((DEVICE_WIDTH * 3) / 20 - 40) / 2,
  },
  videoList: {
    flexDirection: "column",
    justifyContent: "flex-start",
    alignItems: "center",
    marginBottom: 20,
  },
  //删除图标的位置信息
  deleteimage: {
    position: "absolute",
    zIndex: 5,
    right: DEVICE_WIDTH / 20,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  //最后一列删除图标的位置信息
  lastcoldeleteimage: {
    position: "absolute",
    zIndex: 5,
    right: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  deletevideo: {
    position: "absolute",
    zIndex: 5,
    right: 0,
    top: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  downloadvideo: {
    position: "absolute",
    zIndex: 5,
    left: 0,
    top: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  addimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    backgroundColor: "#efefef",

    marginBottom: DEVICE_WIDTH / 20,
    alignItems: "center",
    justifyContent: "center",
  },
  smalladdimage: {
    width: DEVICE_WIDTH / 11,
    height: DEVICE_WIDTH / 11,
    backgroundColor: "#efefef",

    marginRight: 2,
    marginBottom: 3,
    alignItems: "center",
    justifyContent: "center",
  },
  singleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginRight: DEVICE_WIDTH / 20,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  lascolsingleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  // 拍照/打开相机背景样式
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalTop: {
    flex: 1,
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalOption: {
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  ModalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
  audiolistStyle: {
    paddingTop: 10,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
  alterView: {
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
});

export default CompleteProblem;
